import Http from "axios";
import qs from "qs";

const ajax = (url, params) => {
  params.url = url;
  return new Promise((resolve, reject) => {
    Http(params)
      .then((res) => {
        if (res.data.code === "-1") {
          // 登录失败code
          setTimeout(() => {
            localStorage.removeItem("local_token");
            window.location.href = "#/login"
          }, 1000);
        }
        if (!res.data.success) {
          reject(res.data.msg);
        }
        resolve(res.data.data);
      })
      .catch((err) => {
        reject(`${err}`);
      });
  });
};

export default {
  request(baseURL) {
    let host = baseURL;
    return function(params) {
    //   const token = localStorage.getItem('local_token');
      params.opts = params.opts || {};
      // let arr = Object.keys(params.opts);
      let apiParams = {};
      Http.defaults.withCredentials = true;
      if (params.method === "get") {
        apiParams = {
          params: params.opts,
          method: params.method
        };
      } else if (params.method === "post") {
        // if (arr.length === 1) {
        apiParams = {
          headers: {
            // 'content-type': 'application/x-www-form-urlencoded'
            "content-type": "application/json"
          },
          data: qs.stringify(params.opts, { arrayFormat: "comma" }),
          method: params.method
        };
        // } else {
        // apiParams = {
        //   headers: {
        //     'content-type': 'application/json',
        //   },
        // dataType: JSON,
        // data: params.opts,
        // method: params.method,
        // };
        // }
      }
      // 使用FormData上传文件时opts为FormData的实例
      if (params.opts instanceof FormData) {
        apiParams = {
          headers: { "content-type": "multipart/form-data" },
          data: params.opts,
          method: params.method
        };
      }
      // apiParams = getSign(apiParams);
      // 可以做一些token之类的操作
      return ajax(host + params.url, apiParams);
    };
  }
}
